import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wowhy/service_locator.dart';
import 'package:wowhy/services/navigate_service.dart';

class PopupLayout extends PopupRoute {
  @override
  Duration get transitionDuration => Duration(milliseconds: 200);
  @override
  bool get opaque => false;
  @override
  bool get barrierDismissible => false;
  @override
  Color get barrierColor =>
      bgColor == null ? Colors.black.withOpacity(0.5) : bgColor;
  @override
  String get barrierLabel => null;
  @override
  bool get maintainState => false;

  double top;
  double bottom;
  double left;
  double right;
  Color bgColor;
  final Widget child;

  PopupLayout({
    Key key,
    this.bgColor,
    @required this.child,
    this.top,
    this.bottom,
    this.left,
    this.right,
  });

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    if (top == null) this.top = 0;
    if (bottom == null) this.bottom = 0;
    if (left == null) this.left = 0;
    if (right == null) this.right = 0;

    return GestureDetector(
      onTap: () {
        // call this method here to hide soft keyboard
        SystemChannels.textInput.invokeMethod('TextInput.hide');
        getIt<NavigateService>().pop();
      },
      child: Material(
        // This makes sure that text and other content follows the material style
        type: MaterialType.transparency,

        // make sure that the overlay content is not cut off
        child: SafeArea(
          bottom: true,
          child: Scaffold(
            backgroundColor: Colors.transparent,
            body: GestureDetector(
              child: _buildOverlayContent(context),
              onTap: () {},
            ),
          ),
        ),
      ),
    );
  }

  //the dynamic content pass by parameter
  Widget _buildOverlayContent(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
        bottom: this.bottom,
        left: this.left,
        right: this.right,
        top: this.top,
      ),
      child: child,
    );
  }

  @override
  Widget buildTransitions(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child,
  ) {
    // You can add your own animations for the overlay content
    return FadeTransition(
      opacity: animation,
      child: child,
      // child: ScaleTransition(
      //   scale: animation,
      //   child: child,
      // ),
    );
  }
}

showPopupWindow({
  @required BuildContext context,
  @required Widget content,
  Rect position,
}) {
  Navigator.push(
    context,
    PopupLayout(
      top: position?.top,
      left: position?.left,
      right: position?.right,
      bottom: position?.bottom,
      child: content,
    ),
  );
}
